//
//  CZOAuthViewController.swift
//  Mircore
//
//  Created by apple on 16/8/9.
//  Copyright © 2016年 飞羽. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking


//  微博AppKey
let WeiboAppKey = "3165859311"
//  微博AppSecret
let WeiboAppSecret = "c495c40b528ffc1e29045073b4b1da71"
//  授权回调页
let WeiboRedirect_Uri = "http://www.itcast.cn"
class CZOAuthViewController: UIViewController {

    //  MARK:   -- 懒加载
    private lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        //  改成透明的
        webView.opaque = false
        //  设置代理
        webView.delegate = self
        view = webView
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        setNavUI()
        requestOAuthLogin()
        
    }
    
    private func setNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(CZOAuthViewController.cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(CZOAuthViewController.autoFillAction))
        navigationItem.title = "微博登录"
        
    }
    
    //  MARK:   --点击事件
    @objc private func cancelAction() {
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    @objc private func autoFillAction() {
        
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'hao123guohaibin@163.com';document.getElementById('passwd').value = 'guohaibin123'")
        
        
    }
    
    
    //  请求第三方登录页面
    private func requestOAuthLogin() {
        //  准备url
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        
        print(url)
        
        //  准备urlRequest
        let urlRequest = NSURLRequest(URL: NSURL(string: url)!)
        
        //  通过webView加载页面
        webView.loadRequest(urlRequest)
        
     }
    
 }
    //  MARK: -UIWebViewDelegate 代理
    extension CZOAuthViewController: UIWebViewDelegate {
        
        //  将要加载请求
        func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
            
            print(request.URL?.absoluteString)
            
            guard let url = request.URL else {
                return false
            }
            
            //  代码执行到此,url一定有值
            
            //  不是以回调页打头, 我不需要关心
            if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
                return true
            }
            //  代码执行到此,是我们的回调页打头
            
            if let query = url.query where query.hasPrefix("code=") {
                //  获取code
                print(query)
                let code = query.substringFromIndex("code=".endIndex)
                print(code)
                FYUserAccountViewModel.sharedUserAccount.reqeustAccessTokenWithCode(code, callBlack: { (isSuccess)  -> () in
                
                if  isSuccess {
                
                  print("登录成功")
                    
                  NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                }else  {
                
                  print("登录失败")
                }
                
            })
                
            }else  {
            
              dismissViewControllerAnimated(true, completion: nil)
            }
            
            return false
        }
        
        //  开始加载
        func webViewDidStartLoad(webView: UIWebView) {
            SVProgressHUD.show()
        }
        
        //  加载完成
        func webViewDidFinishLoad(webView: UIWebView) {
            SVProgressHUD.dismiss()
        }
        
        //  加载失败
        func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
            SVProgressHUD.dismiss()
        }
        
}
